/**
 * 版权所有，侵权必究！
 */

package io.renren.modules.sys.controller;

import com.alibaba.fastjson.JSONObject;
import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.constant.Dict;
import io.renren.common.page.PageData;
import io.renren.common.redis.RedisService;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.security.user.SecurityUser;
import io.renren.modules.security.user.UserDetail;
import io.renren.modules.sys.dto.SysDeptDTO;
import io.renren.modules.sys.entity.SysParamsEntity;
import io.renren.modules.sys.excel.SysDeptExcel;
import io.renren.modules.sys.service.SysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 部门管理
 *
 * @author Mark
 */
@RestController
@RequestMapping("/sys/dept")
@Api(tags = "部门管理")
public class SysDeptController {
	@Autowired
	private SysDeptService sysDeptService;
	@Autowired
	private RedisService redisService;


	/**
	 * 分页查询商户列表
	 *
	 * @param params
	 * @return
	 */
	@GetMapping("page")
	@ApiOperation("分页")
	@ApiImplicitParams({
			@ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType = "int"),
			@ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int"),
			@ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType = "String"),
	})
	@RequiresPermissions("sys:dept:page")
	public Result<PageData<SysDeptDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params) {
		PageData<SysDeptDTO> page = sysDeptService.page(params);
		return new Result<PageData<SysDeptDTO>>().ok(page);
	}

	/**
	 * 查询商户下拉列表
	 *
	 * @param params
	 * @return
	 */
	@GetMapping("list")
	@ApiOperation("列表")
	@RequiresPermissions("sys:dept:list")
	public Result<List<SysDeptDTO>> list(@ApiIgnore @RequestParam Map<String, Object> params) {
		List<SysDeptDTO> list = sysDeptService.list(params);
		return new Result<List<SysDeptDTO>>().ok(list);
	}


	@GetMapping("{id}")
	@ApiOperation("信息")
	@RequiresPermissions("sys:dept:info")
	public Result<SysDeptDTO> get(@PathVariable("id") Long id) {
		SysDeptDTO data = sysDeptService.get(id);
		if (data.getPid() != null) {
			SysDeptDTO sysDeptDTO = sysDeptService.get(data.getPid());
			data.setParentName(sysDeptDTO.getName());
		}
		return new Result<SysDeptDTO>().ok(data);
	}

	@PostMapping
	@ApiOperation("保存")
	@LogOperation("保存")
	@RequiresPermissions("sys:dept:save")
	public Result save(@RequestBody SysDeptDTO dto) {
		//效验数据
		ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
		Result r = sysDeptService.saveDept(dto);
		return r;
	}

	@PutMapping
	@ApiOperation("修改")
	@LogOperation("修改")
	@RequiresPermissions("sys:dept:update")
	public Result update(@RequestBody SysDeptDTO dto) {
		//效验数据
		ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
		sysDeptService.updateDept(dto);
		return new Result();
	}

	@DeleteMapping("{id}")
	@ApiOperation("删除")
	@LogOperation("删除")
	@RequiresPermissions("sys:dept:delete")
	public Result delete(@PathVariable("id") Long id) {
		//效验数据
		AssertUtils.isNull(id, "id");
		sysDeptService.delete(id);
		return new Result();
	}

	@GetMapping("export")
	@ApiOperation("导出")
	@LogOperation("导出")
	@RequiresPermissions("demo:sysdept:export")
	public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
		List<SysDeptDTO> list = sysDeptService.list(params);

		ExcelUtils.exportExcelToTarget(response, null, list, SysDeptExcel.class);
	}

	/**
	 * 分页查询商户列表(包含子级商户)
	 *
	 * @param params
	 * @return
	 */
	@GetMapping("pageList")
	@ApiOperation("分页")
	@ApiImplicitParams({
			@ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType = "int"),
			@ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int"),
			@ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType = "String"),
	})
	@RequiresPermissions("sys:dept:page")
	public Result<PageData<SysDeptDTO>> pageList(@ApiIgnore @RequestParam Map<String, Object> params) {
		PageData<SysDeptDTO> page = sysDeptService.pageList(params);

		return new Result<PageData<SysDeptDTO>>().ok(page);
	}

	@GetMapping("info")
	public Result<Object> getdept() {
		UserDetail user = SecurityUser.getUser();

		SysDeptDTO data = sysDeptService.get(user.getDeptId());
		JSONObject resobj = new JSONObject();
		if (data != null) {
			resobj = (JSONObject) JSONObject.toJSON(data);
			SysParamsEntity serurlparams = redisService.getHashMapClass(Dict.SYSCONFIG, Dict.SERURL, SysParamsEntity.class);
			if (serurlparams != null) {
				resobj.put(Dict.SERURL, serurlparams.getParamValue());
			}
		} else {
			SysParamsEntity serurlparams = redisService.getHashMapClass(Dict.SYSCONFIG, Dict.SERURL, SysParamsEntity.class);
			if (serurlparams != null) {
				resobj.put(Dict.SERURL, serurlparams.getParamValue());
			}
		}
		//JSONObject resobj=JSONObject.(data);

		return new Result<Object>().ok(resobj);
	}
}
